<?php
namespace Home\Controller;
use Think\Controller;
use Think\Verify;
use Home\Common;
/**
 * 注册登录验证
 */
class LoginController extends Controller {
    public function index()
    {
        $this->display('Login/index');
    }

    public function vcode()
    {
        $Verify = new \Think\Verify();
        $Verify->length = 4;
        $Verify->entry();
    }

    public function reg()
    {
        foreach ($_POST as $val) {
            if (empty($val)) {
                $this->error('请完善数据',U('Login/index'),1);
                exit;
            }
        }
        $vcode = I('post.vcode');
        if (!check_verify($vcode)) {
            $this->error('验证码错误',U('Login/index'),1);
            exit;
        }
        $p = D('user');
        if (!$p->create()) {
            $this->error($p->getError(),U('Login/index'),1);
            exit;
        } else {
            $id = $p->add();
            // 同步添加id到个人信息表
            $data['id'] = $id;
            D('userinfo')->add($data);
            $this->success('注册成功',U('Login/index'),1);
            exit;
        }
    }

    public function login()
    {
        foreach ($_POST as $val) {
            if (empty($val)) {
                $this->error('请完善数据',U('Login/index'),1);
                exit;
            }
        }
        $vcode = I('post.vcode');
        if (!check_verify($vcode)) {
            $this->error('验证码错误',U('Login/index'),1);
            exit;
        }
        $password = md5(I('post.pass'));
        $name = I('post.name');
        $user = D('user');
        $u = $user->getByName($name);
        if (!$u) {
            $this->error('用户名不存在',U('Login/index'),1);
        } elseif ($password != $u['pass']) {
            $this->error('密码错误',U('Login/index'),1);
        } else {
            $home['id'] = $u['id'];
            $home['name'] = $u['name'];
            $home['image'] = $u['image'];
            session('verify_code', null);
            session('verify_time', null);
            session('home',$home);
            $this->redirect('Index/index');
        }
    }

    public function logout()
    {
        session('home', null);
        $this->redirect('Login/index');
    }

    public function repass()
    {
        $name = $_POST['name'];
        $user = D('User');
        $userinfo = $user->getByName($name);
        if (!$userinfo || $_POST['tel'] !== $userinfo['tel']) {
            $this->error('手机号码不正确');
            exit;
        }
        unset($_POST['name']);
        if (!$user->create()) {
            $this->error($user->getError());
            exit;
        }
        $id['id'] = $userinfo['id'];

        $user->where($id)->save();
        $this->success('密码修改成功',U('Login/index'));

    }
}